package com.eystar.pdc.controller;

import com.alibaba.fastjson.JSONArray;
import com.eystar.ext.route.ControllerBind;
import com.eystar.pdc.aop.auth.AuthAnno;
import com.eystar.pdc.aop.auth.AuthAnno.AuthType;
import com.eystar.pdc.aop.log.LogAnno;
import com.eystar.pdc.aop.log.LogAnno.LogType;
import com.eystar.pdc.model.Dic;
import com.jfinal.kit.Ret;

import cn.hutool.core.util.StrUtil;

/**
 * Dic 管理 
 * @author Zhangjian
 *
 */
@ControllerBind(controllerKey="/dic", viewPath="/pdc")
@AuthAnno(type = AuthType.Super, res = "dic")
public class DicController extends BaseController {

	/**
	 * 列表展示页面
	 * @throws Exception
	 */
	@AuthAnno(auth="look")
	@LogAnno(desc = "查看字典列表", type = LogType.SEARCH)
	public void index() throws Exception{
		render("dic_list.html");
	}
	
	/**
	 * 树形结构展示
	 * @throws Exception
	 */
	public void tree() throws Exception{
		JSONArray array = Dic.dao.listDicJson();
		renderJson(array);
	}
	
	/**
	 * 跳转到添加页面
	 * @throws Exception
	 */
	@AuthAnno(auth="save")
	public void add() throws Exception{
		render("dic_form.html");
	}
	
	/**
	 * 点击保存按钮
	 * @throws Exception
	 */
	@AuthAnno(auth="save")
	@LogAnno(desc = "添加字典${dic.dic_value}", type = LogType.SAVE)
	public void save() throws Exception{
		Dic dic = null;
		try {
			dic = getSaveModel(Dic.class);
			if (Dic.dao.findFirstByColumn("dic_code", dic.get("dic_code")) != null) {
				renderJson(fail("字典键重复！"));
				return;
			}
			if (StrUtil.isBlank(dic.getStr("parent_id"))) {
				dic.set("parent_id", "0");
			}
			if (StrUtil.isBlank(dic.getStr("memo"))) {
				dic.set("memo", dic.getStr("dic_value"));
			}
			dic.save();
			Ret ret = ok();
			ret.set("id", dic.get("id"));
			ret.set("code", dic.get("dic_code"));
			ret.set("text", dic.get("dic_value"));
			renderJson(ret);
		} catch (Exception e) {
			logger.error("保存出错！", e);
			renderJson(fail());
		}
	}
	
	/**
	 * 跳转到修改页面
	 * @throws Exception
	 */
	@AuthAnno(auth="update")
	public void edit() throws Exception{
		setAttr("dic", Dic.dao.findById(getPara()));
		render("dic_form.html");
	}
	
	/**
	 * 点击修改按钮
	 * @throws Exception
	 */
	@AuthAnno(auth="update")
	@LogAnno(desc = "修改字典${dic.dic_value}", type = LogType.UPDATE)
	public void update() throws Exception{
		Dic dic = null;
		try {
			dic = getUpdateModel(Dic.class);
			dic.update();
			Ret ret = ok();
			ret.set("code", dic.get("dic_code"));
			ret.set("text", dic.get("dic_value"));
			renderJson(ret);
		} catch (Exception e) {
			logger.error("修改出错！" + dic.toJson(), e);
			renderJson(fail());
		}
	}
	
	/**
	 * 删除方法
	 */
	@AuthAnno(auth="delete")
	@LogAnno(desc = "删除字典", type = LogType.DELETE)
	public void delete() throws Exception {
		try {
			Dic.dao.deleteByIds(getPara());
			renderJson(ok());
		} catch (Exception e) {
			logger.error("删除出错！", e);
			renderJson(fail());
		}
	}
}